/*
 * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: CC0-1.0
 */

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_timer.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_vendor.h"
#include "esp_lcd_panel_ops.h"
#include "driver/gpio.h"
#include "esp_err.h"
#include "esp_log.h"
#include "lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "esp_lcd_touch.h"
#include "lcd_touch_ns2009.h"
#include "lcd_bk_aw9523b.h"
#include "tslib.h"

#include "ui_app_clibrate_tp.h"

#include "driver/ledc.h"

#define LEDC_TIMER     LEDC_TIMER_0
#define LEDC_MODE      LEDC_LOW_SPEED_MODE
#define LEDC_OUTPUT_IO (42)                 // Define the output GPIO
#define LEDC_CHANNEL   LEDC_CHANNEL_0
#define LEDC_DUTY_RES  LEDC_TIMER_13_BIT    // Set duty resolution to 13 bits
#define LEDC_DUTY      (4095)               // Set duty to 50%. ((2 ** 13) - 1) * 50% = 4095
#define LEDC_FREQUENCY (2500)               // Frequency in Hertz. Set frequency at 5 kHz

#if CONFIG_EXAMPLE_LCD_TOUCH_ENABLED
#include "driver/i2c.h"
#endif

static const char* TAG = "example";

/* Macro Definition
********************************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// Please update the following configuration according to your LCD spec //////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if CONFIG_EXAMPLE_LCD_I80_COLOR_IN_PSRAM
// PCLK frequency can't go too high as the limitation of PSRAM bandwidth
#define EXAMPLE_LCD_PIXEL_CLOCK_HZ (20 * 1000 * 1000)
#else
#define EXAMPLE_LCD_PIXEL_CLOCK_HZ (20 * 1000 * 1000)
#endif    // CONFIG_EXAMPLE_LCD_I80_COLOR_IN_PSRAM

#define EXAMPLE_LCD_BK_LIGHT_ON_LEVEL  1
#define EXAMPLE_LCD_BK_LIGHT_OFF_LEVEL !EXAMPLE_LCD_BK_LIGHT_ON_LEVEL
#define LCD_PIN_NUM_DATA0              8
#define LCD_PIN_NUM_DATA1              3
#define LCD_PIN_NUM_DATA2              46
#define LCD_PIN_NUM_DATA3              9
#define LCD_PIN_NUM_DATA4              10
#define LCD_PIN_NUM_DATA5              11
#define LCD_PIN_NUM_DATA6              12
#define LCD_PIN_NUM_DATA7              13
#if CONFIG_EXAMPLE_LCD_I80_BUS_WIDTH > 8
#define LCD_PIN_NUM_DATA8  14
#define LCD_PIN_NUM_DATA9  15
#define LCD_PIN_NUM_DATA10 16
#define LCD_PIN_NUM_DATA11 17
#define LCD_PIN_NUM_DATA12 18
#define LCD_PIN_NUM_DATA13 19
#define LCD_PIN_NUM_DATA14 20
#define LCD_PIN_NUM_DATA15 21
#endif
#define LCD_PIN_NUM_PCLK     21//14
#define LCD_PIN_NUM_CS       48
#define LCD_PIN_NUM_DC       14//21
#define LCD_PIN_NUM_RST      47
#define LCD_PIN_NUM_BK_LIGHT 38

// The pixel number in horizontal and vertical
#define LCD_H_RES 320
#define LCD_V_RES 480

#define LCD_BUFFER_H LCD_H_RES
#define LCD_BUFFER_V LCD_V_RES

// Bit number used to represent command and parameter
#if CONFIG_EXAMPLE_LCD_I80_CONTROLLER_R61581
#define LCD_CMD_BITS   8
#define LCD_PARAM_BITS 8
#endif

#if CONFIG_EXAMPLE_LCD_TOUCH_ENABLED
#define EXAMPLE_I2C_NUM 0    // I2C number
#define EXAMPLE_I2C_SCL 39
#define EXAMPLE_I2C_SDA 40
#endif

#define EXAMPLE_LVGL_TICK_PERIOD_MS 2

// Supported alignment: 16, 32, 64. A higher alignment can enables higher burst transfer size, thus a higher i80 bus throughput.
#define EXAMPLE_PSRAM_DATA_ALIGNMENT 64


/* Function Declaration
********************************************************************************************************/
static void                   app_lcd_bk_config(void);
static esp_lcd_panel_handle_t app_lcd_init(void* p_arg);
static void                   app_touch_init(esp_lcd_touch_handle_t* tp, esp_lcd_panel_io_handle_t* tp_io_handle);
extern void                   example_lvgl_demo_ui(lv_disp_t* disp);
static bool                   example_notify_lvgl_flush_ready(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_io_event_data_t* edata, void* user_ctx);
static void                   example_lvgl_flush_cb(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* color_map);
static void                   example_lvgl_touch_cb(lv_indev_drv_t* drv, lv_indev_data_t* data);
static void                   example_increase_lvgl_tick(void* arg);

static void tslib_touch_init(void);


/* Structure Definition
********************************************************************************************************/



/* Global Variables
********************************************************************************************************/
static esp_lcd_touch_handle_t    tp             = NULL;
static esp_lcd_panel_io_handle_t tp_io_handle   = NULL;
bool                             g_tp_clibreted = false;


/* Public Functions
********************************************************************************************************/
void app_main(void)
{
    static lv_disp_draw_buf_t disp_buf;    // contains internal graphic buffer(s) called draw buffer(s)
    static lv_disp_drv_t      disp_drv;    // contains callback functions
    // static esp_lcd_touch_handle_t    tp           = NULL;
    // static esp_lcd_panel_io_handle_t tp_io_handle = NULL;
    static esp_lcd_panel_handle_t panel_handle = NULL;

    app_lcd_bk_config();
    panel_handle = app_lcd_init((void*)&disp_drv);

    tslib_touch_init();
    // app_touch_init(&tp, &tp_io_handle);

    ESP_LOGI(TAG, "Initialize LVGL library");
    lv_init();
    // alloc draw buffers used by LVGL
    // it's recommended to choose the size of the draw buffer(s) to be at least 1/10 screen sized
    lv_color_t* buf1 = NULL;
    lv_color_t* buf2 = NULL;
#if CONFIG_EXAMPLE_LCD_I80_COLOR_IN_PSRAM
    buf1 = heap_caps_aligned_alloc(EXAMPLE_PSRAM_DATA_ALIGNMENT, LCD_H_RES * LCD_BUFFER_V * sizeof(lv_color_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
#else
    buf1 = heap_caps_malloc(LCD_H_RES * LCD_BUFFER_V * sizeof(lv_color_t), MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
#endif
    assert(buf1);
#if CONFIG_EXAMPLE_LCD_I80_COLOR_IN_PSRAM
    buf2 = heap_caps_aligned_alloc(EXAMPLE_PSRAM_DATA_ALIGNMENT, LCD_H_RES * LCD_BUFFER_V * sizeof(lv_color_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
#else
    buf2 = heap_caps_malloc(LCD_H_RES * LCD_BUFFER_V * sizeof(lv_color_t), MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
#endif
    assert(buf2);
    ESP_LOGI(TAG, "buf1@%p, buf2@%p", buf1, buf2);
    // initialize LVGL draw buffers
    lv_disp_draw_buf_init(&disp_buf, buf1, buf2, LCD_H_RES * LCD_BUFFER_V);

    ESP_LOGI(TAG, "Register display driver to LVGL");
    lv_disp_drv_init(&disp_drv);
    disp_drv.hor_res   = LCD_H_RES;
    disp_drv.ver_res   = LCD_V_RES;
    disp_drv.flush_cb  = example_lvgl_flush_cb;
    disp_drv.draw_buf  = &disp_buf;
    disp_drv.user_data = panel_handle;
    lv_disp_t* disp    = lv_disp_drv_register(&disp_drv);

    ESP_LOGI(TAG, "Install LVGL tick timer");

    // Tick interface for LVGL (using esp_timer to generate 2ms periodic event)
    const esp_timer_create_args_t lvgl_tick_timer_args = {
        .callback = &example_increase_lvgl_tick,
        .name     = "lvgl_tick"};

    esp_timer_handle_t lvgl_tick_timer = NULL;
    ESP_ERROR_CHECK(esp_timer_create(&lvgl_tick_timer_args, &lvgl_tick_timer));
    ESP_ERROR_CHECK(esp_timer_start_periodic(lvgl_tick_timer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000));

#if CONFIG_EXAMPLE_LCD_TOUCH_ENABLED
    static lv_indev_drv_t indev_drv;    // Input device driver (Touch)
    lv_indev_drv_init(&indev_drv);
    indev_drv.type    = LV_INDEV_TYPE_POINTER;
    indev_drv.disp    = disp;
    indev_drv.read_cb = example_lvgl_touch_cb;
    // indev_drv.user_data = tp;

    lv_indev_drv_register(&indev_drv);
#endif

    ESP_LOGI(TAG, "Display LVGL animation");
    // example_lvgl_demo_ui(disp);
    // lv_demo_benchmark();
    // lv_demo_widgets();
    lv_demo_music();

    app_page_create(lv_scr_act());

    while(1)
    {
        // raise the task priority of LVGL and/or reduce the handler period can improve the performance
        vTaskDelay(pdMS_TO_TICKS(1));
        // The task running lv_timer_handler should have lower priority than that running `lv_tick_inc`
        lv_timer_handler();
    }
}


/* Private Functions
********************************************************************************************************/

static bool example_notify_lvgl_flush_ready(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_io_event_data_t* edata, void* user_ctx)
{
    lv_disp_drv_t* disp_driver = (lv_disp_drv_t*)user_ctx;
    lv_disp_flush_ready(disp_driver);
    return false;
}

static void example_lvgl_flush_cb(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* color_map)
{
    esp_lcd_panel_handle_t panel_handle = (esp_lcd_panel_handle_t)drv->user_data;
    int                    offsetx1     = area->x1;
    int                    offsetx2     = area->x2;
    int                    offsety1     = area->y1;
    int                    offsety2     = area->y2;
    // copy a buffer's content to a specific area of the display
    esp_lcd_panel_draw_bitmap(panel_handle, offsetx1, offsety1, offsetx2 + 1, offsety2 + 1, color_map);
}

#if CONFIG_EXAMPLE_LCD_TOUCH_ENABLED

// typedef void (*p_func_ts_input)(uint16_t*, uint16_t*);

static int ts_raw_input(uint16_t* x, uint16_t* y)
{
    uint16_t touchpad_x[1] = {0};
    uint16_t touchpad_y[1] = {0};
    uint8_t  touchpad_cnt  = 0;

    /* Read touch controller data */
    esp_lcd_touch_read_data(tp);

    /* Get coordinates */
    bool touchpad_pressed = esp_lcd_touch_get_coordinates(tp, touchpad_x, touchpad_y, NULL, &touchpad_cnt, 1);

    *x = touchpad_x[0];
    *y = touchpad_y[0];

    return touchpad_pressed;
}


static void tslib_touch_init(void)
{
    app_touch_init(&tp, &tp_io_handle);

    ts_set_raw_input_cb(ts_raw_input);
    ts_open(NULL, 0);
}


static void example_lvgl_touch_cb(lv_indev_drv_t* drv, lv_indev_data_t* data)
{
    // uint16_t touchpad_x[1] = {0};
    // uint16_t touchpad_y[1] = {0};
    // uint8_t  touchpad_cnt  = 0;

    // /* Read touch controller data */
    // esp_lcd_touch_read_data(drv->user_data);
    struct ts_sample samp;
    // ts_read(NULL, &samp);

    if(g_tp_clibreted)
    {
        ts_read(NULL, &samp, 1);
    }
    else
    {
        ts_read_raw(NULL, &samp, 1);
    }

    if(samp.pressure >= 70)
    {
        data->point.x = samp.x;
        data->point.y = samp.y;
        data->state   = LV_INDEV_STATE_PRESSED;
    }
    else
    {
        data->state = LV_INDEV_STATE_RELEASED;
    }

    // ESP_LOGI(TAG, "touch cb: %d,%d,press:%d\n", samp.x, samp.y, samp.pressure);

    // /* Get coordinates */
    // bool touchpad_pressed = esp_lcd_touch_get_coordinates(drv->user_data, touchpad_x, touchpad_y, NULL, &touchpad_cnt, 1);
    // bool touchpad_pressed = true;

    // if(touchpad_pressed && touchpad_cnt > 0)
    // {
    //     data->point.x = touchpad_x[0];
    //     data->point.y = touchpad_y[0];
    //     data->state   = LV_INDEV_STATE_PRESSED;
    // }
    // else
    // {
    //     data->state = LV_INDEV_STATE_RELEASED;
    // }
}
#endif


static void example_increase_lvgl_tick(void* arg)
{
    /* Tell LVGL how many milliseconds has elapsed */
    lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
}


static void example_ledc_init(void)
{
    // Prepare and then apply the LEDC PWM timer configuration
    ledc_timer_config_t ledc_timer = {
        .speed_mode      = LEDC_MODE,
        .timer_num       = LEDC_TIMER,
        .duty_resolution = LEDC_DUTY_RES,
        .freq_hz         = LEDC_FREQUENCY,    // Set output frequency at 5 kHz
        .clk_cfg         = LEDC_AUTO_CLK};
    ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));

    // Prepare and then apply the LEDC PWM channel configuration
    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_MODE,
        .channel    = LEDC_CHANNEL,
        .timer_sel  = LEDC_TIMER,
        .intr_type  = LEDC_INTR_DISABLE,
        .gpio_num   = LEDC_OUTPUT_IO,
        .duty       = 0,    // Set duty to 0%
        .hpoint     = 0};
    ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
}


/**
 ********************************************************************************************************
 * @brief   app_lcd_bk_config
 *
 ********************************************************************************************************
 **/
static void app_lcd_bk_config(void)
{
    ESP_LOGI(TAG, "Turn off LCD backlight");

    // example_ledc_init();
    // ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, LEDC_DUTY));

    gpio_config_t bk_gpio_config = {
        .mode         = GPIO_MODE_OUTPUT,
        .pin_bit_mask = 1ULL << LCD_PIN_NUM_BK_LIGHT};

    ESP_ERROR_CHECK(gpio_config(&bk_gpio_config));
    gpio_set_level(LCD_PIN_NUM_BK_LIGHT, EXAMPLE_LCD_BK_LIGHT_OFF_LEVEL);

    ESP_LOGI(TAG, "Turn on LCD backlight");
    gpio_set_level(LCD_PIN_NUM_BK_LIGHT, EXAMPLE_LCD_BK_LIGHT_ON_LEVEL);
}

/**
 ********************************************************************************************************
 * @brief   app_lcd_init
 *
 ********************************************************************************************************
 **/
static esp_lcd_panel_handle_t app_lcd_init(void* p_arg)
{
    ESP_LOGI(TAG, "Initialize Intel 8080 bus");

    esp_lcd_i80_bus_handle_t i80_bus    = NULL;
    esp_lcd_i80_bus_config_t bus_config = {
        .clk_src        = LCD_CLK_SRC_DEFAULT,
        .dc_gpio_num    = LCD_PIN_NUM_DC,
        .wr_gpio_num    = LCD_PIN_NUM_PCLK,
        .data_gpio_nums = {
                           LCD_PIN_NUM_DATA0,
                           LCD_PIN_NUM_DATA1,
                           LCD_PIN_NUM_DATA2,
                           LCD_PIN_NUM_DATA3,
                           LCD_PIN_NUM_DATA4,
                           LCD_PIN_NUM_DATA5,
                           LCD_PIN_NUM_DATA6,
                           LCD_PIN_NUM_DATA7,
#if CONFIG_EXAMPLE_LCD_I80_BUS_WIDTH > 8
                           LCD_PIN_NUM_DATA8,
                           LCD_PIN_NUM_DATA9,
                           LCD_PIN_NUM_DATA10,
                           LCD_PIN_NUM_DATA11,
                           LCD_PIN_NUM_DATA12,
                           LCD_PIN_NUM_DATA13,
                           LCD_PIN_NUM_DATA14,
                           LCD_PIN_NUM_DATA15,
#endif
                           },
        .bus_width          = CONFIG_EXAMPLE_LCD_I80_BUS_WIDTH,
        .max_transfer_bytes = LCD_H_RES * LCD_BUFFER_V * sizeof(uint16_t),
        .psram_trans_align  = EXAMPLE_PSRAM_DATA_ALIGNMENT,
        .sram_trans_align   = 4,
    };

    ESP_ERROR_CHECK(esp_lcd_new_i80_bus(&bus_config, &i80_bus));
    esp_lcd_panel_io_handle_t     io_handle = NULL;
    esp_lcd_panel_io_i80_config_t io_config = {
        .cs_gpio_num       = LCD_PIN_NUM_CS,
        .pclk_hz           = EXAMPLE_LCD_PIXEL_CLOCK_HZ,
        .trans_queue_depth = 10,
        .dc_levels         = {
                              .dc_idle_level  = 0,
                              .dc_cmd_level   = 0,
                              .dc_dummy_level = 0,
                              .dc_data_level  = 1,
                              },
        .flags = {
                              .swap_color_bytes = !LV_COLOR_16_SWAP,    // Swap can be done in LvGL (default) or DMA
        },
        .on_color_trans_done = example_notify_lvgl_flush_ready,
        .user_ctx            = p_arg, //&disp_drv,
        .lcd_cmd_bits        = LCD_CMD_BITS,
        .lcd_param_bits      = LCD_PARAM_BITS,
    };
    ESP_ERROR_CHECK(esp_lcd_new_panel_io_i80(i80_bus, &io_config, &io_handle));

    esp_lcd_panel_handle_t panel_handle = NULL;

    ESP_LOGI(TAG, "Install LCD driver of r61581");
    esp_lcd_panel_dev_config_t panel_config = {
        .reset_gpio_num = LCD_PIN_NUM_RST,
        .rgb_endian     = LCD_RGB_ENDIAN_RGB,
        .bits_per_pixel = 16,
    };
    ESP_ERROR_CHECK(esp_lcd_new_panel_r61581(io_handle, &panel_config, &panel_handle));

    esp_lcd_panel_reset(panel_handle);
    esp_lcd_panel_init(panel_handle);
    // Set inversion, x/y coordinate order, x/y mirror according to your LCD module spec
    // the gap is LCD panel specific, even panels with the same driver IC, can have different gap value
    // esp_lcd_panel_invert_color(panel_handle, true);
    esp_lcd_panel_set_gap(panel_handle, 0, 0);

    // user can flush pre-defined pattern to the screen before we turn on the screen or backlight
    ESP_ERROR_CHECK(esp_lcd_panel_disp_on_off(panel_handle, true));

    return panel_handle;
}

/**
 ********************************************************************************************************
 * @brief   app_touch_init
 *
 ********************************************************************************************************
 **/
static void app_touch_init(esp_lcd_touch_handle_t* tp, esp_lcd_panel_io_handle_t* tp_io_handle)
{
#if CONFIG_EXAMPLE_LCD_TOUCH_ENABLED
    // esp_lcd_touch_handle_t    tp           = NULL;
    // esp_lcd_panel_io_handle_t tp_io_handle = NULL;

    if(tp == NULL || tp_io_handle == NULL)
    {
        return;
    }

    ESP_LOGI(TAG, "Initialize I2C");

    const i2c_config_t i2c_conf = {
        .mode             = I2C_MODE_MASTER,
        .sda_io_num       = EXAMPLE_I2C_SDA,
        .scl_io_num       = EXAMPLE_I2C_SCL,
        .sda_pullup_en    = GPIO_PULLUP_ENABLE,
        .scl_pullup_en    = GPIO_PULLUP_ENABLE,
        .master.clk_speed = 100000,
    };
    /* Initialize I2C */
    ESP_ERROR_CHECK(i2c_param_config(EXAMPLE_I2C_NUM, &i2c_conf));
    ESP_ERROR_CHECK(i2c_driver_install(EXAMPLE_I2C_NUM, i2c_conf.mode, 0, 0, 0));

    esp_lcd_panel_io_i2c_config_t tp_io_config = ESP_LCD_TOUCH_IO_I2C_NS2009_CONFIG();

    ESP_LOGI(TAG, "Initialize touch IO (I2C)");

    /* Touch IO handle */
    ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c((esp_lcd_i2c_bus_handle_t)EXAMPLE_I2C_NUM, &tp_io_config, tp_io_handle));

    esp_lcd_touch_config_t tp_cfg = {
        .x_max        = LCD_H_RES,
        .y_max        = LCD_V_RES,
        .rst_gpio_num = -1,
        .int_gpio_num = -1,
        .flags        = {
                         .swap_xy  = 0,
                         .mirror_x = 0,
                         .mirror_y = 0,
                         },
        .process_coordinates = NULL,
    };

    /* Initialize touch */
    ESP_LOGI(TAG, "Initialize touch controller NS2009");
    ESP_ERROR_CHECK(esp_lcd_touch_new_i2c_ns2009(*tp_io_handle, &tp_cfg, tp));
#endif
}


/* End Of File
********************************************************************************************************/
